import Taro from '@tarojs/taro';
import {Image, View, Text, Swiper, SwiperItem, Button, RichText} from '@tarojs/components';
import {connect} from "@tarojs/redux";
import {appConfig, request, unite} from '../../../utils/index';
import './courseDetail.scss';
import TrainIcon1 from "../../../asset/images/train_icon1.png";
import TrainIcon2 from "../../../asset/images/train_icon2.png";
import TrainIcon3 from "../../../asset/images/train_icon3.png";
import TrainIcon4 from "../../../asset/images/train_icon4.png";
import Home1 from "../../../asset/images/homes.png";
import AiIn from "../../../asset/images/ai_in.png";
import Ai from "../../../asset/images/ai.png";
import Fb from "../../../asset/images/fb.png";
import {actionCreator} from "../../../store/actions";
import UnionidModal from "../../../components/unionid-modal/unionidModal";

class CourseDetail extends Taro.Component {
    config = {
        navigationBarTitleText: '课程详情',
        navigationBarBackgroundColor: '#ffffff',
        // enablePullDownRefresh: true
    };

    state = {
        unionId: false,
        detailData: [], //课程详情
        classRoom: [], //教室信息，
        coachInfo: [], //教练详情
        money: 0, //余额
        heights: 0,
    };

    componentDidMount() {
        //classId, dispatchId
        this.getDetail();
        this.init()
    }

    //获取用户信息
    init = () => {
        const params = {
            url: '/wx/firstPage/getUserDetail',
            data:{}
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data) {
                        this.setState({
                            money: Number(res.data.accountBalance), //获取余额
                        })
                    }
                }
            }
        })
    };

    //获取课程详情
    getDetail = () => {
        const option = this.$router.params;
        console.log(option);
        const params = {
            url: '/wx/firstPage/getClassDetail',
            data:{
                classId: option.classId,
                dispatchId: option.dispatchId,
            }
        };
        request(params).then(res => {
            if (res) {
                if(res.code == 200) {
                    if (res && res.data && res.data.classRoom) {
                        this.setState({
                            detailData: res.data,
                            classRoom: res.data.classRoom,
                            coachInfo: res.data.coachInfo,
                            reservedStatus: res.data.reservedStatus
                        }, () => {
                            let query = wx.createSelectorQuery();
                            setTimeout(() => {
                                var heig = 0;
                                query.selectAll('.head-imgs').boundingClientRect(rect=>{
                                    // heig = rect.height;
                                    console.log(rect);
                                    rect.forEach((item) => {
                                        console.log(item.height);
                                        console.log(Number(item.height) > Number(heig));
                                        if (Number(item.height) > Number(heig)) {
                                            heig = item.height;
                                        }
                                    });
                                    this.setState({
                                        heights: heig
                                    }, () => {
                                        console.log(this.state.heights)
                                    })
                                }).exec();

                            },500);
                        })
                    }
                }
            }
        })
    };

    //跳转教练详情
    skipTrainDetail = () => {
        const {coachInfo} = this.state;
        Taro.navigateTo({
            url: '../train-detail/trainDetail?id=' + coachInfo.coachId
        })
    };

    //教练收藏 取消收藏
    collect = (e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        const {coachInfo} = this.state;
        if (coachInfo.collectionStatus == 0) {
            const params = {
                url: '/wx/collection/save',
                data:{
                    collectionTypeCode: '02', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: coachInfo.coachId,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        unite.showToast('收藏成功');
                        this.getDetail() //获取课程列表
                    }
                }
            })
        } else {
            const params = {
                url: '/wx/collection/deleteById',
                data:{
                    collectionTypeCode: '02', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: coachInfo.coachId,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        unite.showToast('已取消收藏');
                        this.getDetail() //获取课程列表
                    }
                }
            })
        }
    };

    //课程收藏 取消收藏
    collectNext = () => {
        const {detailData} = this.state;
        if (detailData.collectionStatus == 0) {
            const params = {
                url: '/wx/collection/save',
                data:{
                    collectionTypeCode: '01', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: detailData.dispatchId,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        unite.showToast('收藏成功');
                        this.getDetail() //获取课程列表
                    }
                }
            })
        } else {
            const params = {
                url: '/wx/collection/deleteById',
                data:{
                    collectionTypeCode: '01', //收藏类型编码 （01 课程收藏、02 教练收藏、03 教室好收藏）
                    relateKeyId: detailData.dispatchId,
                }
            };
            request(params).then(res => {
                if (res) {
                    if(res.code == 200) {
                        unite.showToast('已取消收藏');
                        this.getDetail() //获取课程列表
                    }
                }
            })
        }
    };

    //跳转确认订单页面
    skipAffirm = () => {
        const {money,detailData} = this.state;
        const option = this.$router.params;
        // if (option.reservedStatus != 0) return unite.showToast('该课程已约满');
        if (money < Number(detailData.price)) return unite.showToast('您的余额不足，请充值');
        Taro.navigateTo({
            url: '../affirm-detail/affirmDetail?classId=' + option.classId + '&dispatchId=' + option.dispatchId
        });
    };

    //跳转教室详情
    goToDetail = () => {
        const {classRoom} = this.state;
        Taro.navigateTo({
            url: `../classroom-detail/classroomDetail?id=${classRoom.roomId}&avatar=${classRoom.avatar}&roomName=${classRoom.roomName}&address=${classRoom.address}&latitude=${classRoom.latitude}&longitude=${classRoom.longitude}`
        })
    };

    //跳转教室地图导航
    goToMap = (e) => {
        e.stopPropagation(); //防止父级点击事件干扰
        const {classRoom} = this.state;
        if (classRoom.latitude) {
            Taro.openLocation({
                latitude: Number(classRoom.latitude),
                longitude: Number(classRoom.longitude),
                name: classRoom.roomName,
                address: classRoom.address
            })
        } else {
            unite.showToast('该店铺暂无经纬度');
        }
    };

    //锚点跳转
    skipPageScro = () => {
        Taro.pageScrollTo({
            selector: '#buyNote',
            duration: 300
        })
    };

    //分享
    onShareAppMessage () {
        const option = this.$router.params;
        return {
            title: '动态镜子',
            path:  `pages/index/course-detail/courseDetail?classId=${option.classId}&dispatchId=${option.dispatchId}`
        }
    }

    //跳转套餐充值
    skipMeal = () => {
        const {existUser} = this.props;
        if (existUser == 0) { //未授权用户信息
            this.setState({
                unionId: true
            });
            return;
        }
        Taro.navigateTo({
            url: `../../my/meal-list/mealList`
        })
    };

    unGetUserInfo = (is) => {
        const {setExistUser} = this.props;
        if (is) {
            setExistUser(1);
            Taro.navigateTo({
                url: `../../my/meal-list/mealList`
            })
        }
        this.setState({
            unionId: false, //关闭 nu ni id 弹窗
        });
    };

    render() {
        const {detailData, classRoom, coachInfo, reservedStatus, money, unionId, heights} = this.state;
        return (
            <View className="page">
                <View className="course-logo">
                    <View>
                        <Swiper
                            className='test-h'
                            indicatorColor='rgba(0, 0, 0, 0.2)'
                            indicatorActiveColor='#FFFFFF'
                            circular
                            style={'height: 0px; overflow: hidden;'}
                            indicatorDots
                        >
                            {detailData.avatars.map((item, index) => (
                                <SwiperItem key={index}>
                                    <Image
                                        className="head-imgs"
                                        mode="widthFix"
                                        src={item}
                                    />
                                </SwiperItem>
                            ))}
                        </Swiper>
                    </View>
                    {heights && (
                        <Swiper
                            className='test-h'
                            indicatorColor='rgba(0, 0, 0, 0.2)'
                            indicatorActiveColor='#FFFFFF'
                            circular
                            style={'height:' + heights + 'px;'}
                            indicatorDots
                            autoplay
                        >
                            {detailData.avatars.map((item, index) => (
                                <SwiperItem key={index}>
                                    <Image
                                        className="keep-head-img"
                                        mode="widthFix"
                                        src={item}
                                    />
                                </SwiperItem>
                            ))}
                        </Swiper>
                    )}
                    <Image className="head-ai" onClick={this.collectNext} src={detailData.collectionStatus != 0 ? AiIn : Ai} mode="aspectFit"/>
                    <Button className="head-fb"  open-type="share">
                        <Image className="head-fb-img" src={Fb} onClick={this.onShareAppMessage} mode="aspectFit"/>
                    </Button>
                </View>
                <View className="course-head">
                    <View className="select-items-wrap flex-lr">
                        <View className="items-list items-list-avtive">
                            <View>课程信息</View>
                            <View className="heng"></View>
                        </View>
                        <View className="items-list" onClick={this.skipPageScro}>
                            <View>注意事项</View>
                            <View className="heng"></View>
                        </View>
                    </View>
                    <View className="select-gn-wrap">
                        <View className="name">{detailData.className || '暂无名称'}</View>
                        <View className="flex-top detail-names" onClick={this.skipTrainDetail}>
                            <Image className="head-img" src={coachInfo.avatar || appConfig.picurl+'/cam/assets/img/energy-ny/banner_head.png'}/>
                            <View className="titlest">
                                <View className="title-name">{coachInfo ? coachInfo.coachName || '暂无名称' : '暂无名称'}</View>
                                <View>{coachInfo.profile}</View>
                            </View>
                        </View>
                        <View className="train-lists-wrap">
                            <View className="train-lists flex-l">
                                <Image className="icon-img" src={TrainIcon1} mode="aspectFit"/>
                                <View className="titls">时间</View>
                                <View>{detailData.classDate + ' '+ detailData.classWeekDay + ' ' + detailData.classBeginTime + ' - ' + detailData.classEndTime}</View>
                            </View>
                            <View className="train-lists flex-l">
                                <Image className="icon-img" src={TrainIcon2} mode="aspectFit"/>
                                <View className="titls">人数</View>
                                <View>{detailData.reservedInfo}</View>
                            </View>
                        </View>
                        <View className="address-lists-wrap flex-lr" onClick={this.goToDetail.bind(this, classRoom.roomId,classRoom.avatar,classRoom.roomName,classRoom.address,classRoom.latitude, classRoom.longitude)}>
                            <View className="flex-l">
                                <Image className="icon-img" src={Home1} mode="aspectFit"/>
                                <View className="titls">门店</View>
                                <View className="titles-detail">
                                    <View className="td-names">{classRoom ? classRoom.roomName : ''}</View>
                                </View>
                            </View>
                            <View className="arrow"></View>
                        </View>
                        <View className="address-lists-wrap address-lists-wrap-none flex-lr" onClick={this.goToMap}>
                            <View className="flex-l">
                                <Image className="icon-img" src={TrainIcon3} mode="aspectFit"/>
                                <View className="titls">地址</View>
                                <View className="titles-detail">
                                    <View className="text-overflow">{classRoom ? classRoom.address : ''}</View>
                                </View>
                            </View>
                            <View className="arrow"></View>
                        </View>
                    </View>
                    <View className="select-detail-wrap">
                        <View className="text">课程简介</View>
                        <View className="title">{detailData ? detailData.describeInfo : ''}</View>
                        <View className="flex-l kepp-gg-wrap">
                            {detailData.labelNames && detailData.labelNames.map((item, index) => (
                                <View className="kepp-gg flex-center" key={index}>{item}</View>
                            ))}
                        </View>
                        <View className="text" id="buyNote">适宜人群</View>
                        <View className="title">{detailData.suitCorwd}</View>
                        <View className="text">配套设施</View>
                        <View className="flex-l  pt-wrap">
                            {detailData.deviceType && detailData.deviceType.map((item, index) => (
                                <View className="pt-item" key={index}>
                                    <Image className="pt-icon" src={item.picUrl} mode="aspectFit"/>
                                    <View>{item.name}</View>
                                </View>
                            ))}
                        </View>
                        <View className="text" id="buyNote">注意事项</View>
                        <RichText className="title" nodes={detailData.remark}></RichText>
                        <View className={`sumbit-btn flex-center ${money >= detailData.price ? 'sumbit-btn-active' : ''}`} onClick={this.skipAffirm}>立刻预约 ¥{detailData ? detailData.price : 0}</View>
                        {money < detailData.price &&(
                            <View className="flex-l tishi-title" onClick={this.skipMeal}>
                                <View className="quan flex-center">!</View>
                                <View>您的余额不够预约课程！去充值  >></View>
                            </View>
                        )}
                    </View>
                    {unionId &&(
                        <UnionidModal onCancel={this.unGetUserInfo}/>
                    )}
                </View>
            </View>
        )
    }
}

const mapStateToProps = state => {
    let {existUser} = state;
    return {
        existUser
    }
};

const mapDispatchToProps = {
    setExistUser: actionCreator.setExistUser,
};

export default connect(mapStateToProps, mapDispatchToProps)(CourseDetail);



